package com.example.rocketmq.demo.producer;

import com.example.rocketmq.demo.config.RocketMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 顺序消息生产者
 */
@Slf4j
@Component
public class OrderlyProducer {

    @Autowired
    @Qualifier("defaultMQProducer")
    private DefaultMQProducer producer;

    /**
     * 发送顺序消息
     *
     * @param content 消息内容
     * @param orderId 订单ID（用于选择队列）
     * @return 发送结果
     */
    public SendResult sendOrderly(String content, Long orderId) throws Exception {
        Message message = new Message(
                RocketMQConstant.TOPIC_ORDER,
                RocketMQConstant.TAG_ORDER,
                content.getBytes(StandardCharsets.UTF_8)
        );

        // 使用订单ID作为分区键，确保同一订单的消息进入同一队列
        SendResult sendResult = producer.send(message, new MessageQueueSelector() {
            @Override
            public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                Long id = (Long) arg;
                int index = (int) (id % mqs.size());
                return mqs.get(index);
            }
        }, orderId);

        log.info("顺序消息发送结果: {}, orderId: {}", sendResult, orderId);
        return sendResult;
    }
}
